#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_
#include <thread>
#include <vector>
#include <future>
#include <atomic>
#include <queue>
#include <memory>
#include <condition_variable>
// C++ thread_pool ---> need set thread num
class Thread_pool {
public:
	using Task = std::packaged_task<void()>;
	static Thread_pool& Instance() {
		static Thread_pool ins;
		return ins;
	}
	template <class F, class ...Args>
	auto commit(F&& f, Args && ...args) -> std::future<decltype(f(args...))> {
		using Rettype = decltype(f(args...));
		auto task = std::make_shared<std::packaged_task<void()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
		auto res = task->get_future();
		{
			std::lock_guard<std::mutex> lk(m);
			tasks.emplace([this, task]() {
				(*task)();
				});
			/*tasks.push(std::move(*task));*/
		}
		cv.notify_one();
		return res;
	}
private:
	Thread_pool(unsigned int num = 5) :thread_num(num), _stop(false) {
		start();
	}
	~Thread_pool() {
		stop();
	}
	void start() {
		for (int i = 0; i < thread_num; i++) {
			_pool.emplace_back([this]() {
				while (!_stop.load()) {
					Task task;
					{
						std::unique_lock<std::mutex> lk(m);
						cv.wait(lk, [this]() {
							return _stop.load() || !tasks.empty();
							});
						if (tasks.empty() && _stop.load()) {
							return;
						}
						task = std::move(tasks.front());
						tasks.pop();
					}
					thread_num--;
					task();
					thread_num++;
				}
				});
		}
	}
	void stop() {
		_stop.store(true);
		cv.notify_all();
		for (auto& t : _pool) {
			if (t.joinable()) {
				t.join();
			}
		}
	}
private:
	std::atomic_int thread_num;
	std::atomic_bool _stop;
	std::vector<std::thread> _pool;
	std::queue<Task> tasks;
	std::mutex m;
	std::condition_variable cv;
};
#endif // _THREAD_POOL_H_

